import React from 'react';

export interface MessageInstance {
    info: (text: string) => void;
    warn: (text: string) => void;
    error: (text: string) => void;
    success: (text: string) => void;
}

class Message {
    static info(text: string) {
        useMessage((instance) => {
            instance.info(text);
        });
    }

    static error(text: string) {
        useMessage((instance) => {
            instance.error(text);
        });
    }

    static warn(text: string) {
        useMessage((instance) => {
            instance.warn(text);
        });
    }

    static success(text: string) {
        useMessage((instance) => {
            instance.success(text);
        });
    }
};

export default Message;

function useMessage(func: (message: MessageInstance) => void) {
    let instance = window['__MESSAGE__'] && window['__MESSAGE__'].default;
    if (instance) {
        func(instance);
        return;
    }

    loadModule().then(() => {
        useMessage(func);
    });
}

const loadModule = (): Promise<any> => {
    return new Promise((resolve) => {
        window['__MESSAGE__IMPORTER']().then((mod) => {
            window['__MESSAGE__'] = mod;
            resolve(mod);
        });
    });
};

export const initialize = (importer: () => Promise<any>): void => {
    window['__MESSAGE__IMPORTER'] = importer;
};
